import Vue from "vue";
import Vuex from 'vuex'
import getters from "./getters";

Vue.use(Vuex)
const store = new Vuex.Store({
  getters,
  state: {
    cartList: []
  },
  mutations: {
    addCounter(state, payload) {
      payload.count+=1
    },
    addToCart(state, payload) {
      state.cartList.push(payload)
    }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((resolve,reject)=>{
        let oldProduct = context.state.cartList.find(item => item.iid === payload.iid)
        payload.checked=true
        if (oldProduct) {
          context.commit('addCounter', oldProduct)
          resolve("商品数量加一")
        } else {
          payload.count = 1
          context.commit('addToCart', payload)
          resolve("已经添加到购物车")
        }
      })
    }
  }
})
export default store
